var sendReq = new Array();
var receiveReq = new Array();
var checkReqStatusReq = new Array();

var onlineUsersReq = getXmlHttpRequestObject();
var startConversationReq = getXmlHttpRequestObject();
var checkIncomingReq = getXmlHttpRequestObject();
var replyToChatReq = getXmlHttpRequestObject();
var deleteIncomReq = getXmlHttpRequestObject();
var logoutReq = getXmlHttpRequestObject();
var closeReq = getXmlHttpRequestObject();

sendReq[0] = getXmlHttpRequestObject();
receiveReq[0] = getXmlHttpRequestObject();
checkReqStatusReq[0] = getXmlHttpRequestObject();

var lastMessage = new Array();
lastMessage[0]= 0;
var getchat_served = 0;
var chat_id = new Array();
var rcTimer = new Array();
var mTimer;
var uTimer;
var incomingTimer;
var total_tabs;


//Function for initializating the page.
function startChat() {
	total_tabs = 0;
    
	// initialize first tab
	//total_tabs++;
	//addtab(total_tabs);
	    
	$("#addtab, #litab").click(function() {
		total_tabs++;
		$("#tabcontent div").hide();
		addtab(total_tabs);
		return false;
	});

	//Start Receiving List of Online Users
	getOnlineUsers();
	//Start checking incoming chat requests
	checkIncomingChat();
	//Start Receving Messages.
	//getChatText();
}
		
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		document.getElementById('p_status').innerHTML = 'Status: Upgrade your browser.';
	}
}

//Gets the current messages from the server
function getChatText(tab) {
	
	    if (receiveReq[tab].readyState == 4 || receiveReq[tab].readyState == 0) {
			receiveReq[tab].open("GET", '/InstantMessaging/GetMessage?chat='+chat_id[tab]+'&last='+lastMessage[tab], true);
			receiveReq[tab].onreadystatechange = function(){ handleReceiveChat(tab); }; 
			receiveReq[tab].send(null);
	    }			
}

//Function for handling the return of chat text
function handleReceiveChat(tab_num) {
	if (receiveReq[tab_num].readyState == 4) {
		var chat_div = document.getElementById('div_chat-'+tab_num);
		var xmldoc = receiveReq[tab_num].responseXML;
		
		if(xmldoc){
			var message_nodes = xmldoc.getElementsByTagName("message");		
			var n_messages = message_nodes.length;
			for (var i = 0; i < n_messages; i++) {
				var user_node = message_nodes[i].getElementsByTagName("user");
				var text_node = message_nodes[i].getElementsByTagName("text");
				var time_node = message_nodes[i].getElementsByTagName("time");
				chat_div.innerHTML += '<font size="2"> <i>' + time_node[0].firstChild.nodeValue + '</i></font>';
				chat_div.innerHTML += '<font size="2"> <b>' + user_node[0].firstChild.nodeValue +': </b> </font>';
				chat_div.innerHTML += text_node[0].firstChild.nodeValue + '<br />';
				chat_div.scrollTop = chat_div.scrollHeight;
				lastMessage[tab_num] = (message_nodes[i].getAttribute('id'));
			}			
		}
		mTimer = setTimeout('getChatText('+tab_num+');',3000); //Refresh chat in 3 seconds		
	}
}

//Add a message to the chat server.
function sendChatText(tab_num) { //tab_num is the number of current tab
	if(document.getElementById('txt_message-'+tab_num).value == '') {
		alert("You have not entered a message");
		return;
	}
	if (sendReq[tab_num].readyState == 4 || sendReq[tab_num].readyState == 0) {
		sendReq[tab_num].open("POST", '/InstantMessaging/SendMessage?last=' + lastMessage[tab_num], true);
		sendReq[tab_num].setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq[tab_num].onreadystatechange = function(){ handleSendChat(tab_num); };  
		var param = 'message=' + document.getElementById('txt_message-'+tab_num).value;
		var id = chat_id[tab_num];
		param += '&chat='+id;
		sendReq[tab_num].send(param);
		document.getElementById('txt_message-'+tab_num).value = '';
	}							
}

//When our message has been sent, update our page.
function handleSendChat(tab) {
	//Clear out the existing timer so we don't have 
	//multiple timer instances running.
	clearInterval(mTimer);
	clearInterval(uTimer);
	getChatText(tab);
}

function getOnlineUsers() {
	if (onlineUsersReq.readyState == 4 || onlineUsersReq.readyState == 0) {
		onlineUsersReq.open("GET", '/InstantMessaging/GetOnlineUsers', true);
		onlineUsersReq.onreadystatechange = handleGetOnlineUsers; 
		onlineUsersReq.send(null);
	}
}

function handleGetOnlineUsers() { 
	if(onlineUsersReq.readyState==4){
		var contact_div = document.getElementById('div_contact');
		var xmldoc = onlineUsersReq.responseXML;
		
		if(xmldoc){
			var user_nodes = xmldoc.getElementsByTagName("online_users");		
			var n_users = user_nodes.length;
			contact_div.innerHTML ='';
			for (var i = 0; i < n_users; i++) {
				var user_node = user_nodes[i].getElementsByTagName("user");
				var user = user_node[0].firstChild.nodeValue;
				contact_div.innerHTML += '<a href="javascript:;" onclick="StartConversation('+'\''+user+'\''+')">'+user_node[0].firstChild.nodeValue+'</a>'+'<br>';
			}
		}
		uTimer = setTimeout('getOnlineUsers();',10000); //Refresh our online users list in 10 seconds
	}
}

//Send chat request to a contact
function StartConversation(receiver) {
	if (startConversationReq.readyState == 4 || startConversationReq.readyState == 0) {
		total_tabs++;
		tabnum = total_tabs;
		lastMessage[tabnum] = 0; //TODO: Sarebbe meglio unificare queste operazioni, nella creazione tab
		$("#tabcontent div").hide();
		addtab(tabnum,receiver);
		receiveReq[tabnum] = getXmlHttpRequestObject();
		sendReq[tabnum] = getXmlHttpRequestObject();
		checkReqStatusReq[tabnum] = getXmlHttpRequestObject();
		startConversationReq.open("GET", '/InstantMessaging/StartConversation?receiver='+receiver+'&tabnum='+tabnum, true);
		startConversationReq.onreadystatechange = function(){ handleStartConversation(receiver,tabnum); };
		startConversationReq.send(null);
	}
}

function handleStartConversation(receiver, tabnum){
	if(startConversationReq.readyState==4){
		checkReqStatus(receiver,tabnum);
	}
}
//Check "new conversation" request status
function checkReqStatus(receiver,tab_num) {
	var tabnum = tab_num;
	if (checkReqStatusReq[tabnum].readyState == 4 || checkReqStatusReq[tab_num].readyState == 0) {
		checkReqStatusReq[tabnum].open("GET", '/InstantMessaging/CheckReqStatus?receiver='+receiver, true);
		checkReqStatusReq[tabnum].onreadystatechange = function(){ handleCheckReqStatus(tabnum); };
		checkReqStatusReq[tabnum].send(null);
	};
}

function handleCheckReqStatus(tabnum) { 
	if(checkReqStatusReq[tabnum].readyState==4){
		
		var xmldoc = checkReqStatusReq[tabnum].responseXML;
		var conn_accepted='NULL';
		var name ='';
		var id = 0;
		
		if(xmldoc){
			var request_nodes = xmldoc.getElementsByTagName("request");
			var n_req = request_nodes.length;
			for (var i = 0; i < n_req; i++) {
				name = request_nodes[i].getElementsByTagName("name")[0].firstChild.nodeValue;
				conn_accepted = request_nodes[i].getElementsByTagName("accepted")[0].firstChild.nodeValue;
				id = request_nodes[i].getElementsByTagName("chat_id")[0].firstChild.nodeValue;
			}
			
			var chat_div = document.getElementById('div_chat-'+tabnum);

			if(conn_accepted=='true'){ //if user accept chat request
				//Mapping chat_id --> num tab
				chat_id[tabnum] = id;
			    chat_div.innerHTML = name+ ' READY to chat <br>';
			    getChatText(tabnum);
			
			}else if(conn_accepted=='NULL'){ //else if user there's no response from user
			    chat_div.innerHTML = 'Waiting response from '+name+'..<br>';
			    var s = "'"+name+"'";
			    rcTimer[tabnum] = setTimeout('checkReqStatus('+s+','+tabnum+');',3000); //Check request state in 3 seconds
			
			}else if(conn_accepted=='false'){ //else if user refuse chat request
			    chat_div.innerHTML = name+ ' NOT AVAILABLE <br>'; 	
			}
		}
	}
}

//These functions will be used for check if there are some incoming Chat request
function checkIncomingChat(){
	if (checkIncomingReq.readyState == 4 || checkIncomingReq.readyState == 0) {
		checkIncomingReq.open("GET", '/InstantMessaging/CheckIncoming?', true);
		checkIncomingReq.onreadystatechange = handleCheckIncomingChat;
		checkIncomingReq.send(null);
	    }
}

function handleCheckIncomingChat(){
	if(checkIncomingReq.readyState==4){
		var xmldoc = checkIncomingReq.responseXML;
		
		if(xmldoc){
			var requestor_node = xmldoc.getElementsByTagName("requestor");
			var num_req = requestor_node.length;
			for (var i = 0; i<num_req; i++){
				var requestor = requestor_node[i].firstChild.nodeValue;
				
				//Show confirmation dialog (chat request confirmation)
				if(confirm('Accept chat request from '+requestor+' ?')){
					replyToChatReq.open("GET",'/InstantMessaging/CreateChat?accept=true&sender='+requestor,true);
					//alert('Richiesta accettata');
					replyToChatReq.onreadystatechange = handleReplyToChat;
					replyToChatReq.send(null);
				}else{
					replyToChatReq.open("GET",'/InstantMessaging/CreateChat?accept=false&sender='+requestor,true);
					//alert('Richiesta rifiutata');
					replyToChatReq.send(null);
				}
				
			}				
		}
		incomingTimer = setTimeout('checkIncomingChat();',10000); //Refresh check Incoming chat every 10 seconds
	}
}

function handleReplyToChat(){
	
	if(replyToChatReq.readyState==4){	
		var xmldoc = replyToChatReq.responseXML;
		if(xmldoc){
			var id = xmldoc.getElementsByTagName("chat_id")[0].firstChild.nodeValue;
			var requestor = xmldoc.getElementsByTagName("requestor")[0].firstChild.nodeValue;
			total_tabs++;
			tabnum = total_tabs;
			lastMessage[tabnum]=0;
			receiveReq[tabnum] = getXmlHttpRequestObject();
			sendReq[tabnum] = getXmlHttpRequestObject();
			$("#tabcontent div").hide();
			addtab(tabnum,requestor);
			chat_id[tabnum] = id;
			getChatText(tabnum);
		}
	}
}

function closeChat(user2) {
	
    if (closeReq.readyState == 4 || closeReq.readyState == 0) {
		closeReq.open("GET", '/InstantMessaging/CloseChat?user2='+user2, true);
		//closeReq.onreadystatechange = function(){ handleReceiveChat(tab); }; 
		closeReq.send(null);
    }			
}

//Ask confirm if user close window
window.onbeforeunload = confirmExit;
function confirmExit(){
	 if (logoutReq.readyState == 4 || logoutReq.readyState == 0) {
			logoutReq.open("GET", '/InstantMessaging/Logout', true);
			logoutReq.send(null);
	    }	
}

function addtab(count,receiver) {
        var closetab = '<a href="javascript:;" onclick="closeChat('+'\''+receiver+'\''+')" id="close'+count+'" class="close">&times;</a>';
        $("#tabul").append('<li id="t'+count+'" class="ntabs">'+receiver+' &nbsp;&nbsp;'+closetab+'</li>');
        $("#tabcontent").append(
		'<div id="c'+count+'">'+
			'<p id="div_chat-'+count+'" style="overflow: auto; width: 100%; height: 85%; background:white;"></p>'+
			'<input class="text_chat" type="text" id="txt_message-'+count+'"' 
			+'onkeydown="if (event.keyCode == 13) document.getElementById(\'btn_send_chat-'+count+'\').click()" style="width: 70%;" />'+
			'<input type="button" id="btn_send_chat-'+count+'" value="Send" onclick="javascript:sendChatText('+count+');" />'+
		'</div>'
);
        //style="overflow: auto; width: 100%; height: 100%; background: white; z-index:1000;"
        $("#tabul li").removeClass("ctab");
        $("#t"+count).addClass("ctab");
        
        $("#t"+count).bind("click", function() {
            $("#tabul li").removeClass("ctab");
            $("#t"+count).addClass("ctab");
            $("#tabcontent div").hide();
            $("#c"+count).fadeIn('slow');
        });
        
        $("#close"+count).bind("click", function() {
	    total_tabs--;	
            // activate the previous tab
            $("#tabul li").removeClass("ctab");
            $("#tabcontent div").hide();
            $(this).parent().prev().addClass("ctab");
            $("#c"+count).prev().fadeIn('slow');
            
            $(this).parent().remove();
            $("#c"+count).remove();
            return false;
        });
}
